package com.selftool.main;

import com.selftool.bo.DosBO;
import com.selftool.bo.FromBO;
import com.selftool.gui.serverframe.MainFrom;
import com.selftool.log.Logger;
import com.selftool.util.CommonUtil;

/** 业务中介类 */
public class Intermediary {
    public DosBO dosbo = null;
    public FromBO frombo = null;
    public MainFrom dialog = null;
    public Intermediary(){
        this.dosbo =  new DosBO(this);
        this.frombo =  new FromBO(this);
    }

    public void setDialog(MainFrom dialog) {
        this.dialog = dialog;
    }

    public MainFrom getDialog() {
        return dialog;
    }
    public DosBO getDosbo(){
        return this.dosbo;
    }

    /***
     * 按钮事件执行中介
     * @param str
     * @param from
     * @param obj
     * @return
     * @throws Exception
     */
    public Object exec(String str, MainFrom from,Object obj) throws Exception {
        try{
            aftercheck();
            if("from.SysConfigButton".equals(str)){
                frombo.exeSysConfigButton(from);
            }else if("from.ReStartButton".equals(str)){
                frombo.exeReStartButton(from);
            }else if("from.ClearButton".equals(str)){
                frombo.exeClearButton(from);
            }else if("from.UpdatesButton".equals(str)){
                frombo.exeUpdatesButton(from);
            }else if("dos".equals(str)) {
                //异步调用dos指令,目的是异步刷新dos响应
                class MyThread extends Thread {
                    @Override
                    public void run() {
                        try {
                            getDosbo().exec((String) obj);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                MyThread newThread = new MyThread();
                newThread.start();
            }else{
                throw new Exception("未找到需要代理的指令["+str+"]");
            }
        }catch (Exception e){
            if(from!=null){
                Logger.write("动作处理发生异常,"+e.getMessage()+"\n "+ CommonUtil.errorStackTrace(e));
            }else{
                throw e;
            }
        }
        return null;
    }

    /***
     * 按钮执行前校验
     * @throws Exception
     */
    private void aftercheck() throws Exception {
        String homepath = CommonUtil.getParameter("homepath");
        if(homepath == null||homepath.isEmpty()){
            throw new Exception("当前您未进行工具初始化，请点击初始化配置按钮并选择home！");
        }
    }
}
